/**
 * 
 */
package exp.social.graph.business;

import java.text.ParseException;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import exp.social.graph.dataaccess.DataProviderResult;
import exp.social.graph.model.UserModel;

/**
 * @author Volodya Gavrysh
 * 
 */
public class User extends BusinessObject {
	private UserModel model;

	private User(UserModel model) {
		this.model = model;
	}

	public boolean validate() {
		return true;
	}

	public static User create(String username, String password, ArrayList<Integer> interestsList) {
		UserModel model = new UserModel();
		model.setUsername(username);
		model.setPassword(password);
		model.setInterests(interestsList);
		DataProviderResult<UserModel> result = getDataProvider().createUser(
				model);
		if (result.isSuccess()) {
			return new User(model);
		}
		return null;
	}

	public static boolean remove(Integer userId) {
		UserModel model = new UserModel();
		model.setId(userId);
		DataProviderResult<UserModel> result = getDataProvider().removeUser(
				model);
		return result.isSuccess();
	}

	public static User getById(Integer userId) {
		DataProviderResult<UserModel> result = getDataProvider().getUserById(
				userId);
		if (result.isSuccess()) {
			return new User(result.getResult());
		}
		return null;
	}

	public String getUserName() {
		return model.getUsername();
	}

	public void setUserName(String userName) {
		model.setUsername(userName);
	}

	public Integer getId() {
		return model.getId();
	}

	public String getPassword() {
		return model.getPassword();
	}

	public void setPassword(String password) {
		model.setPassword(password);
	}
	
	public ArrayList<Integer> getInterests() {
		return model.getInterests();
	}

	public void setInterests(ArrayList<Integer> interests) {
		model.setInterests(interests);
	}
	
	public Timeline getTimeline(){
		return null;
	}
	
	public Picture getProfilePicture(){
		//TODO: implement lazy loading
		return null;
	}
	
	public User[] getFriends(){
		return null;
	}

	@Override
	public String toJSON() {
		JSONObject json = new JSONObject();
		json.put("userName", getUserName());
		json.put("id", getId());
		if (model.getInterests() != null) {
			json.put("interests", new JSONArray(model.getInterests()));
		}
		return json.toString();
	}

	public static User fromJSON(String jsonStr) throws ParseException {
		UserModel model = new UserModel();
		JSONObject json = new JSONObject(jsonStr);
		model.setId(json.getInt("id"));
		model.setUsername(json.getString("userName"));
		model.setPassword(json.getString("password"));
		JSONArray interests = json.getJSONArray("interests");
		ArrayList<Integer> interestsList = new ArrayList<Integer>();
		for (int i = 0; i < interests.length(); i++) {
			interestsList.add(interests.getInt(i));
		}
		model.setInterests(interestsList);
		return new User(model);
	}
}
